const DB = require('../core/DB')
const {
    Op
} = require('sequelize')


DB.message.belongsTo(DB.user)
DB.message.hasMany(DB.reply)

DB.comment.belongsTo(DB.user)
DB.comment.belongsTo(DB.article)
DB.comment.hasMany(DB.reply)

DB.reply.belongsTo(DB.comment)
DB.reply.belongsTo(DB.message)



class MsgController {
    /* ------------------------------------- ok 获取所有评论 -----------------------------------------*/
    async searchComment(ctx){
        // 参数
        let {
            page = 1, size = 10, id, status, name
        } = ctx.query

        page = Number(page)
        size = Number(size)

        let params = {}
        if (id) params.id = id
        if (status) params.status = status
        if (name) params.name = {
            [Op.like]: `%${name}%`
        }

        const {
            count,
            rows
        } = await DB.user.findAndCountAll({
            attributes: {
                exclude: ['password']
            },
            where: params,
            offset: (page - 1) * size,
            limit: size
        })

        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        // if (count) {
        global.Response.success(ctx, undefined, data)
        // } else {
        //     global.Response.null(ctx)
        // }
    }
    /* ------------------------------------- ok 获取所有评论 -----------------------------------------*/
    async listComment(ctx) {
        // 参数
        const {
            page = 1, size = 10, key = ''
        } = ctx.query

        const {
            count,
            rows
        } = await DB.comment.findAndCountAll({
            // where: {
            //     title: {
            //         [Op.substring]: key
            //     }
            // },
            offset: (page - 1) * size,
            limit: size,
            include: [{
                model: DB.user,
                attributes: {
                    exclude: 'password'
                }
            }, DB.article]
        })

        const data = {
            rows,
            meta: {
                key,
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)

    }
    /* ----------------------- -----------------ok 更新评论审核状态 ------------------------------------------------- */
    async updateComment(ctx) {
        try {
            const {
                id,
                status
            } = ctx.request.body
            const res = await DB.comment.update({
                status
            }, {
                where: {
                    id
                }
            }) // return [0] or [1]
            if (res[0]) {
                global.Response.success(ctx, '更新成功')
            }
        } catch (err) {
            global.Response.error(ctx, err)
        }
    }
    /* ----------------------------------------- ok 更新留言审核状态 ------------------------------------------------- */
    async updateMessage(ctx) {
        try {
            const {
                id,
                status
            } = ctx.request.body
            const res = await DB.message.update({
                status
            }, {
                where: {
                    id
                }
            }) // return [0] or [1]
            if (res[0]) {
                global.Response.success(ctx, '更新成功')
            }
        } catch (err) {
            global.Response.error(ctx, err)
        }
    }

    /* ------------------------------------------- ok 新建评论 ----------------------------------------------*/
    async createComment(ctx) {
        let {
            userId,
            content,
            articleId
        } = ctx.request.body

        const comment = await DB.comment.create({
            userId,
            content,
            articleId,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        if (comment) {
            global.Response.success(ctx)
        } else {
            global.Response.fail(ctx)
        }
    }

    /* ------------------------------------------------ok  删除评论 --------------------------------------------------------*/
    async deleteComment(ctx) {
        const {
            id
        } = ctx.query
        await DB.comment.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        // 删除评论下的所有回复
        await DB.reply.destroy({ // return 1 or 0
            where: {
                commentId: id
            }
        })

        global.Response.success(ctx, '删除成功')

    }

    /* ------------------------------------------------ ok 新建留言 --------------------------------------------------------*/
    async createMessage(ctx) {
        let {
            userId,
            content,
            status = 1, // 显示or隐藏
        } = ctx.request.body

        const message = await DB.message.create({
            userId,
            content,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        global.Response.success(ctx)
    }

    async listMessage(ctx) {
        // 参数
        let {
            page = 1, size = 10, key = '', admin = 0
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.message.findAndCountAll({
            where: {
                status: {
                    [Op.in]: [0, 1, 2] // 审核状态
                }
            },
            offset: (page - 1) * size,
            limit: size,
            include: [{
                model: DB.user,
                attributes: ['id', 'email', 'name']
            }]
        })

        for (let message of rows) {
            // 获取id 前往reply查找
            let messageId = message.get('id')
            const { count: replyCount, rows: replies } = await DB.reply.findAndCountAll({
                where: {
                    messageId
                }
            })

            message.dataValues.replies = replies || []

            if (replies.length > 0) {
                for (let reply of replies) {
                    let userId = reply.get('userId')
                    let replyUserId = reply.get('replyUserId')
                    // 回复用户
                    let user = await DB.user.findByPk(userId, {
                        attributes: {
                            exclude: ['password', 'createdAt', 'updatedAt']
                        }
                    })
                    // 被回复用户
                    let replyUser = await DB.user.findByPk(replyUserId, {
                        attributes: {
                            exclude: ['password', 'createdAt', 'updatedAt']
                        }
                    })
                    reply.dataValues.user = user
                    reply.dataValues.replyUser = replyUser
                }
            }
            message.dataValues.replyCount = replies.length
        }


        const data = {
            rows,
            meta: {
                key,
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)

    }

    /* ------------------------------------------------ ok 留言列表 --------------------------------------------------------*/
    async listMessage_copy(ctx) {
        // 参数
        let {
            page = 1, size = 10, key = '', admin = 0
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.message.findAndCountAll({
            where: {
                status: {
                    [Op.in]: [0, 1, 2] // 审核状态
                }
            },
            offset: (page - 1) * size,
            limit: size,
            include: [{
                model: DB.user,
                attributes: ['id', 'email', 'name']
            }]
        })





        // 加载回复
        for (let message of rows) {
            // message.dataValues.replies = []
            // 获取id 前往reply查找
            // let messageId = message.get('id')


            // message.dataValues.replies = replies

            // let replies = message.get('replies')
            // if (replies.length > 0) {

            //     for (let reply of replies) {
            //         let userId = reply.get('userId')
            //         let replyUserId = reply.get('replyUserId')
            //         // 回复用户
            //         let user = await DB.user.findByPk(userId, {
            //             attributes: {
            //                 exclude: ['password', 'createdAt', 'updatedAt']
            //             }
            //         })
            //         // 被回复用户
            //         let replyUser = await DB.user.findByPk(replyUserId, {
            //             attributes: {
            //                 exclude: ['password', 'createdAt', 'updatedAt']
            //             }
            //         })
            //         reply.dataValues.user = user
            //         reply.dataValues.replyUser = replyUser
            //     }
            // }
            // message.dataValues.replyCount = replies.length

        }

        const data = {
            // rows,
            // meta: {
            //     key,
            //     page: page, // 当前页数
            //     size, // 每页条目
            //     count: count, // 条目总数
            //     total: Math.ceil(count / size), // 总页数
            // }
        }
        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------------------------------ok 删除留言 --------------------------------------------------------*/
    async deleteMessage(ctx) {
        const {
            id
        } = ctx.query
        let res = await DB.message.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        // 删除评论下的所有回复
        res = await DB.reply.destroy({ // return 1 or 0
            where: {
                messageId: id
            }
        })

        global.Response.success(ctx, '删除成功')

    }

    /* ------------------------------------------------ ok 回复列表 --------------------------------------------------------*/
    async listReply(ctx) {
        // 参数
        const {
            page = 1, size = 10, key = ''
        } = ctx.query

        const {
            count,
            rows
        } = await DB.reply.findAndCountAll({
            // where: {
            //     title: {
            //         [Op.substring]: key
            //     }
            // },
            offset: (page - 1) * size,
            limit: size,
        })


        for (let i in rows) {
            let item = rows[i]
            let userId = item.get('userId')
            let user = await DB.user.findByPk(userId, {
                attributes: {
                    exclude: ['password']
                }
            })
            let replyUserId = item.get('replyUserId')
            let replyUser = await DB.user.findByPk(replyUserId, {
                attributes: {
                    exclude: ['password']
                }
            })
            item.dataValues.user = user
            item.dataValues.replyUser = replyUser
        }

        const data = {
            rows,
            meta: {
                key,
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        global.Response.success(ctx, undefined, data)
    }

    /* ----------------------------------------------- ok 更新回复 审核状态/已读状态 ------------------------------------------------- */
    async updateReply(ctx) {
        try {
            const {
                id,
                status,
                read
            } = ctx.request.body
            const res = await DB.reply.update({
                status,
                read
            }, {
                where: {
                    id
                }
            }) // return [0] or [1]
            if (res[0]) {
                global.Response.success(ctx, '更新成功')
            }
        } catch (err) {
            global.Response.error(ctx, err)
        }
    }

    /* ------------------------------------------------ ok 新建回复 --------------------------------------------------------*/
    async createReply(ctx) {
        const {
            userId,
            replyUserId,
            commentId,
            messageId,
            content,
            status = 1
        } = ctx.request.body

        const reply = await DB.reply.create({
            userId,
            replyUserId,
            commentId,
            messageId,
            content,
            status,
            read: 0, // 未读
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        if (reply) {
            global.Response.success(ctx)
        } else {
            global.Response.fail(ctx)
        }
    }

    /* ------------------------------------------------ok 加载回复 个人收到的回复 --------------------------------------------------------*/
    async loadPersonReply(ctx) {
        const {
            page = 1, size = 10, replyUserId,
        } = ctx.query

        const {
            count,
            rows
        } = await DB.reply.findAndCountAll({
            where: {
                replyUserId
            },
            offset: page - 1,
            limit: size,
        })
        for (let i in rows) {
            let item = rows[i]
            let userId = item.get('userId')
            let user = await DB.user.findByPk(userId, {
                attributes: ['name', 'admin']
            })
            let comment = await DB.comment.findByPk(item.get('commentId'))
            if (comment) {
                item.dataValues.articleId = comment.get('articleId') // 文章Id
            }
            item.dataValues.userName = user.get('name')
            item.dataValues.admin = user.get('admin')
        }
        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------------------------------ok 删除回复 --------------------------------------------------------*/
    async deleteReply(ctx) {
        const {
            id
        } = ctx.query
        const res = await DB.reply.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        if (res) {
            global.Response.success(ctx, '删除成功')
        } else {
            global.Response.null(ctx)
        }

    }


}

module.exports = new MsgController